const Router = require("koa-router");
const { User } = require("@models/user");
const { Auth } = require("@middlewares/auth");
const { wxPay } = require("@services/pay");
const axios = require("axios");
const { Activity } = require("@models/activity");
const { Enroll } = require("@models/enroll");
const { operatorPoint } = require("@services/operatorPoint");
const crypto = require("crypto");



const router = new Router({
  prefix: "/v1/wxpay",
});

// 报名支付
router.post("/enroll/pay", new Auth().m, async (ctx, next) => {
  const { activity_id } = ctx.request.body;
  const enroll = await Enroll.findOne({
    where: {
      activity_id,
      uid: ctx.auth.uid,
    },
  });

  const activity = await Activity.findOne({
    where: {
      activity_id,
    },
  });

  const user = await User.findOne({
    where: {
      uid: ctx.auth.uid,
    },
  });
  if (!user) {
    throw new global.errs.AuthFailed("用户查询失败");
  }

  let data = {
    openid: user.openid,
    total: activity.price,
    description: activity.title,
    out_trade_no: enroll.enroll_number,
  };

  const result = await wxPay.Jsapi(data, ctx);
  ctx.body = result;
});



// 订单详情
router.post("/enroll/order", new Auth().m, async (ctx, next) => {
  const { enroll_number } = ctx.request.body;
  if (!enroll_number) {
    throw new global.errs.AuthFailed("参数错误");
  }
  const enroll = await Enroll.findOne({
    where: {
      enroll_number,
    },
  });
  if (!enroll) {
    throw new global.errs.NotFound("订单不存在");
  }

  let path = `/v3/pay/transactions/out-trade-no/${enroll_number}?mchid=1683029327`;
  let url = `https://api.mch.weixin.qq.com` + path;
  let params = {
    method: "GET",
    path,
    nonce_str: crypto.randomBytes(16).toString("hex"),
    body: "",
  };
  const authorization = await wxPay.authorization(params);
  const res = await axios.get(url, {
    headers: {
      Authorization: authorization,
      Accept: "application/json",
    },
  });

  let status = {
    SUCCESS: 1, // 支付成功
    REFUND: -1, // 转入退款
    NOTPAY: 0, // 未支付
    CLOSED: 2, // 已关闭
  };

  await Enroll.update(
    { enroll_status: status[res.data.trade_state] }, // 1:已支付
    {
      where: {
        enroll_number,
      },
    }
  );

  ctx.body = {
    code: 200,
    msg: "查询成功",
    data: res.data,
  };
});

// // 申请退款
// router.post("/apply_refund", new Auth().m, async (ctx, next) => {
//   await Refund.created();
// });

// 扫码核销
router.post("/scan", new Auth(16).m, async (ctx, next) => {
  const { enroll_number } = ctx.request.body;
  if (!enroll_number) {
    throw new global.errs.AuthFailed("订单号没填");
  }

  const enroll = await Enroll.findOne({ where: { enroll_number } });
  if (enroll.enroll_status == 1) {
    await Enroll.update(
      { enroll_finish: 1 }, // 0:未完成 1:已核销
      {
        where: {
          enroll_number,
        },
      }
    );

    // 更新用户积分
    await operatorPoint.add_scan(Math.ceil(enroll.price / 10), enroll.uid);
    ctx.body = {
      code: 200,
      msg: "核销成功",
    };
  } else {
    throw new global.errs.NotFound("订单没有完成支付");
  }
});

module.exports = router;
